<template>
  <div class="page-crud-demo">
    <CrudPage :title="'用户列表'" :crud="crud">
      <template #query-fields>
        <my-el-input v-model="crud.query.keyword" placeholder="关键字" style="width: 220px;" />
      </template>

      <template #columns>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="age" label="年龄" width="100" />
      </template>

      <template #form="{ model }">
        <my-el-form label-width="80px">
          <my-el-form-item label="姓名">
            <my-el-input v-model="model.name" placeholder="请输入姓名" />
          </my-el-form-item>
          <my-el-form-item label="年龄">
            <my-el-input v-model.number="model.age" type="number" placeholder="请输入年龄" />
          </my-el-form-item>
        </my-el-form>
      </template>
    </CrudPage>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import CrudPage from './CrudPage.vue'
import { usePageCrud } from '@/hooks'

// 模拟 API
let autoId = 1000
const db = Array.from({ length: 37 }).map((_, i) => ({ id: i + 1, name: `用户${i + 1}`, age: 18 + (i % 10) }))

async function apiFetchList({ keyword = '', page = 1, pageSize = 10 }) {
  const rows = db.filter(r => r.name.includes(keyword))
  const start = (page - 1) * pageSize
  const end = start + pageSize
  await new Promise(r => setTimeout(r, 300))
  return { list: rows.slice(start, end), total: rows.length }
}

async function apiCreate(data) {
  await new Promise(r => setTimeout(r, 200))
  const row = { id: ++autoId, ...data }
  db.unshift(row)
  return row
}

async function apiUpdate(id, data) {
  await new Promise(r => setTimeout(r, 200))
  const idx = db.findIndex(r => r.id === id)
  if (idx >= 0) db[idx] = { ...db[idx], ...data }
}

async function apiDelete(id) {
  await new Promise(r => setTimeout(r, 200))
  const idx = db.findIndex(r => r.id === id)
  if (idx >= 0) db.splice(idx, 1)
}

async function apiBatchDelete(ids) {
  await new Promise(r => setTimeout(r, 200))
  for (const id of ids) {
    const i = db.findIndex(r => r.id === id)
    if (i >= 0) db.splice(i, 1)
  }
}

const crud = usePageCrud({
  fetchList: apiFetchList,
  createItem: apiCreate,
  updateItem: apiUpdate,
  deleteItem: apiDelete,
  batchDelete: apiBatchDelete,
  idKey: 'id',
  defaultQuery: { keyword: '' }
})

onMounted(() => crud.getList())
</script>

<style scoped>
.page-crud-demo { padding: 12px; }
</style> 